package com.bdqn.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * XML删除
 *
 * @author LILIBO
 * @since 2024/6/28
 */
public class Test04XmlUpd {

    public static void main(String[] args) {
        String xmlFile = "src/main/java/收藏信息.xml";
        // 创建XML文档解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            // 获得XML文档解析器
            DocumentBuilder builder = factory.newDocumentBuilder();
            // 解析XML文件
            Document document = builder.parse(xmlFile);
            NodeList nodeList = document.getElementsByTagName("Brand");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                String name = element.getAttribute("name");
                if (name.equals("魅族")) {
                    element.setAttribute("name", "MeiZu");
                }
            }

            System.out.println("Brand节点修改成功！");

            // 将创建好的XML保存
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            StreamResult result = new StreamResult(Files.newOutputStream(Paths.get(xmlFile)));
            transformer.transform(domSource, result); // 保存
            System.out.println("XML文档保存成功！");
        } catch (ParserConfigurationException | IOException | SAXException | TransformerException e) {
            e.fillInStackTrace();
        }
    }

}
